<?php

namespace pmvc\mvc;

use pmvc\ioc\ObjectFactory;
use pmvc\ioc\ObjectFactoryAware;
use pmvc\ioc\OrderUtil;
use pmvc\log\Log;
use pmvc\mvc\RequestFilterMapping;
use pmvc\mvc\RequestFilter;
use pmvc\mvc\Request;
use pmvc\util\StringUtil;
use pmvc\util\ReflectionUtil;
use Exception;

class BaseRegexMapping
	implements ObjectFactoryAware {
		
	private $regexMap;
	private $objectFactory;
	private $requiredType;

	public function getMappedObjects($input) {
		$ret = Array();
		foreach ($this->regexMap as $key => $vals) {
			if (StringUtil::matches($key, $input, false)) {
				if (!is_array($vals)) {
					$vals = Array($vals);
				}
				foreach ($vals as $val) {
					$obj = (is_string($val))
						? $this->objectFactory->getObjectById($val)
						: $val;
					if (isset($this->requiredType) && !ReflectionUtil::isInstance($obj, $this->requiredType)) {
						Log::error(__CLASS__, "Object with mapping {0} is not a {1}", $key, $this->requiredType);
						throw new Exception("Object is not an instance of ".$this->requiredType);
					}
					$ret []= new MappedObject($obj, $key);
				}
			}
		}
		OrderUtil::sort($ret);
		return $ret;
	}

	public function getMappedObject($input) {
		foreach ($this->regexMap as $key => $vals) {
			if (StringUtil::matches($key, $input, false)) {
				if (!is_array($vals)) {
					$vals = Array($vals);
				}
				foreach ($vals as $val) {
					$obj = (is_string($val))
						? $this->objectFactory->getObjectById($val)
						: $val;
					if (isset($this->requiredType) && !ReflectionUtil::isInstance($obj, $this->requiredType)) {
						Log::error(__CLASS__, "Object with mapping {0} is not a {1}", $key, $this->requiredType);
						throw new Exception("Object is not an instance of ".$this->requiredType);
					}
					return new MappedObject($obj, $key);
				}
			}
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	public function setObjectFactory(ObjectFactory $objectFactory) {
		$this->objectFactory = $objectFactory;
	}

	public function setRegexMap($regexMap) {
		$this->regexMap = $regexMap;
	}

	public function setRequiredType($requiredType) {
		$this->requiredType = $requiredType;
	}

}

?>